﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Threading;
using System.Windows.Threading;

namespace WpfHero
{
    /// <summary>
    /// Plays an audio stream
    /// </summary>
    public class AudioPlayer
    {
        private readonly string _fileName;
        private readonly MediaPlayer _player;

        /// <summary>
        /// Gets the current position of the player.
        /// </summary>
        /// <value>The position.</value>
        public TimeSpan Position
        {
            get { return _player.Position; }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AudioPlayer"/> class.
        /// </summary>
        /// <param name="file">The audio file to play.</param>
        public AudioPlayer(string file)
        {
            _fileName = file;
            _player = new MediaPlayer();
            _player.Open(new Uri(_fileName));
        }

        /// <summary>
        /// Starts this player.
        /// </summary>
        public void Start()
        {
            //may be bad for sync
            _player.Dispatcher.Invoke(DispatcherPriority.Send, new Action( () => { _player.Play(); }));
        }

        /// <summary>
        /// Stops this player.
        /// </summary>
        public void Stop()
        {
            //may be bad for sync
            _player.Stop();
        }

        public EventHandler MediaEnded;

        /// <summary>
        /// Prepares this instance for instant play
        /// </summary>
        internal void Prepare()
        {
            double tmpVolume = _player.Volume;
            _player.Play();
            _player.Volume = 0;
            
            //HACK: make sure the player has initialized
            //play the song for a while silently.
            Thread.Sleep(1000);
            _player.Pause();

            //reset to original value and position.
            _player.Volume = tmpVolume;
            _player.Position = TimeSpan.FromMilliseconds(0);
            _player.MediaEnded += delegate
                                      {
                                          if (MediaEnded != null)
                                              MediaEnded(this, new EventArgs());
                                      };
        }
    }
}
